package net.itheima.mm.controller;

import lombok.extern.slf4j.Slf4j;
import net.itheima.mm.common.GlobalConst;
import net.itheima.mm.entity.Result;
import net.itheima.mm.pojo.User;
import net.itheima.mm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User param, HttpServletRequest request){
        log.info("[用户-登陆]username:{}",param.getUsername());

        //1.获取用户
        User user =userService.findByUsername(param.getUsername());
        //2.用户不存在或密码错误
        if (null==user|| !user.getPassword().equals(param.getPassword())){
            return new Result(false,"用户名不存在或密码错误");
        }

        //3.密码正确，更新session
        HttpSession session= request.getSession(true);
        session.setAttribute(GlobalConst.SESSION_KEY_USER,user);
        return new Result(true, GlobalConst.ACTION_SUCCESS);
    }
    @ResponseBody
    @GetMapping("/logout")
    public Result logintout(HttpServletRequest request){
        log.info("[用户登出]");
        HttpSession session = request.getSession();
        session.removeAttribute("param");
        return new Result(false,"");
    }

}
